package com.bwie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtils;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Prod;
import com.bwie.mapper.ProdMapper;
import com.bwie.service.ProdService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

@Service
@Transactional
public class ProdServiceImpl extends ServiceImpl<ProdMapper, Prod> implements ProdService{
    @Autowired
    private ProdMapper prodMapper;
    @Autowired
    private HttpServletRequest request;
    @Override
    public R getProdList(PageInfoVo pageInfoVo) {
        Page<Prod> prodPage = new Page<>(pageInfoVo.getPageNum(),pageInfoVo.getPageSize());
        Page<Prod> prodPage1 = prodMapper.selectProdList(prodPage,pageInfoVo);
        return R.OK(prodPage1);
    }

    @Override
    public R addProd(Prod prod) {
        Prod prod1 = prodMapper.selectOne(
                new QueryWrapper<Prod>().lambda().eq(Prod::getProdName, prod.getProdName())
                        .or().eq(Prod::getProdSpu,prod.getProdSpu())
        );
        if(ObjectUtils.isNotEmpty(prod1)){
            return R.ERROR(500,"商品已存在");
        }
        String token = request.getHeader("token");
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token)
                .getBody();
        String userName = body.get("userName", String.class);
        prod.setCreateBy(userName);
        prod.setCreateTime(new Date());
        prodMapper.insert(prod);
        return R.OK();
    }
}
